package cn.lfzj.controller;


import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.lfzj.model.User;
import cn.lfzj.service.UserService;

@CrossOrigin
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;

	/**
	 * 查全部用户
	 */
	@RequestMapping("showUser")
	public String selAllUser(Model model, String username) {
		model.addAttribute("UserList", userService.selByUsername(username));
		return "manager/showUser";
	}

	/**
	 * 用户注册
	 */
	@RequestMapping(value = "reg", produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String reg(@Valid User user, BindingResult result) {
		JSONObject json = new JSONObject();
		if (result.hasErrors()) {
			json.put("code", 2);
		} else {
			json.put("code", userService.reg(user));
		}
		return json.toJSONString();
	}

	/**
	 * 用户登录
	 */
	@RequestMapping(value = "login", produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String login(@Valid User user, BindingResult result) {
		JSONObject json = new JSONObject();
		if (result.hasErrors()) {
			json.put("code", 2);
		} else {
			json.put("user", userService.login(user));
		}
		return json.toJSONString();
	}

	/**
	 * 用户充值
	 */
	@RequestMapping("getMoney")
	@ResponseBody
	public String getMoney(String userId,double addMoney) {
		JSONObject json = new JSONObject();
		json.put("code", userService.getMoney(userId,addMoney));
		return json.toJSONString();
	}

	/**
	 * 查余额
	 */
	@RequestMapping("selMoney")
	@ResponseBody
	public String selMoney(int userId) {
		JSONObject json = new JSONObject();
		json.put("money", userService.selMoney(userId));
		return json.toJSONString();
	}

	/**
	 * 用户改密
	 */
	@RequestMapping(value = "updPwd", produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String updPwd(String password, int userId, String oldPassword) {
		JSONObject json = new JSONObject();
		json.put("code", userService.updPwd(password, userId, oldPassword));
		return json.toJSONString();
	}
}
